import makeUserTempId from '@/utils/userTempId'
import { setToken, getToken, removeToken } from '@/utils/token'
import { userLogin, getUserInfo, UserLoginOut } from '@/api'
const state = {
    tempId: makeUserTempId(),
    // 此时token在刷新时会直接消失
    // 所以需要使用local持久化
    token: getToken() || '',
    userInfo: {}
}
const mutations = {
    setToken(state, payload) {
        state.token = payload.token
        setToken(payload.token)
    },
    setUserInfo(state, payload) {
        state.userInfo = payload
    },
    loginOut(state) {
        // 删除vuex以及localtion中的所有token和用户信息
        state.userInfo = {}
        state.token = ''
        removeToken()
    }
}
const actions = {
    async setToken({ commit }, payload) {
        try {
            let re = await userLogin(payload)
            commit('setToken', re)
        } catch (error) {
            // 返回返回,必须返回
            return Promise.reject(error)
        }
    },
    async Userinfo({ commit }, payload) {
        try {
            let re = await getUserInfo(payload)
            commit('setUserInfo', re)
        } catch (error) {
            // 后来发现是在vuex的action函数中已经对错误进行了处理,就不会向上抛出错误,所以需要手动抛出
            return Promise.reject(error)
        }
    },
    async loginOut({ commit }) {
        try {
            await UserLoginOut()
            commit('loginOut')
        } catch (error) {
            console.log(error);
        }
    }
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}